<?php
/**
* 微信服务器配置启用
*/
class Wechat extends MY_Controller
{
	
	function __construct()
	{
		parent::__construct();
		defined('WECHAT_TOKEN') OR define('WECHAT_TOKEN', 'ezrs2018ezrs2018ezrs2018');
	}

	/**
	 * 微信服务器消息入口
	 * @return [type] [description]
	 */
	function index()
	{
		//如果有echostr表示是服务器启用验证
		if (isset($_GET['echostr'])) {
			$this->checkWeixin();
		} else {
			$this->handleEvent();
		}
	}

	/**
	 * 微信服务器启用验证
	 * @return [type] [description]
	 */
	function checkWeixin()
	{
	  	//微信会发送4个参数到我们的服务器后台 签名 时间戳 随机字符串 随机数
	  	$signature = $_GET['signature'];
	  	$timestamp = $_GET['timestamp'];
	  	$nonce = $_GET['nonce'];
	  	$echostr = $_GET['echostr'];
	 
	  	// 1）将token、timestamp、nonce三个参数进行字典序排序
	  	$tmpArr = array($nonce,WECHAT_TOKEN,$timestamp);
	  	sort($tmpArr,SORT_STRING);
	 
	  	// 2）将三个参数字符串拼接成一个字符串进行sha1加密
	  	$str = implode($tmpArr);
	  	$sign = sha1($str);
	 
	  	// 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	  	if ($sign == $signature) {
	   		echo $echostr;
	  	}
	}
 	

 	
	/**
	 * 处理微信事件
	 * @return [type] [description]
	 */
 	function handleEvent()
 	{	
 		$postStr = file_get_contents("php://input");
 		if (!empty($postStr)) {
 			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 
      		$MsgType = trim($postObj->MsgType);
      		
      		switch ($MsgType) {
      			case 'event':
      				//事件类型
      				$result= $this->receiveEvent($postObj);
      				break;
      			default:
      				//回复特定的消息
      				$result= $this->responseMsg($postObj);
      				break;
      		}
      		echo $result;
 		} else {
 			echo 'sucess';
 		}
 	}

 	/*
		取消关注事件
 	*/
	function unsubscribe($openid){
		// $this->db->update('member', array('subcribe' => 0))->where(array('open_id'=>$openid));
		return 'sucess';
	}

 	/**
 	 * 接受微信事件处理
 	 * @return [type] [description]
 	 */
 	function receiveEvent($object)
 	{	
 		$content = '';
 		switch ($object->Event) 
 		{
			//关注事件
 			case 'subscribe':

	 			// 判断是否扫描动态二维码
	 			if (isset($object->EventKey) && !empty($object->EventKey)) {
	 				$title = "Hello".$object->EventKey;

		  			$result = $this->transmitText($object,$title); 
	 			} else {
	 				$title = "Hello World";
	  			
		  			$result = $this->transmitText($object,$title); 
	 			}

 				break;

 			// 取关事件
 			case 'unsubscribe':

 				$content = $this->unsubscribe($object->FromUserName);

		 		$result = $this->transmitText($object,$content); 

 				break;

 			// 已关注事件
 			case 'SCAN':
                $title = "Hello World";
             
                $result = $this->transmitText($object,$title); 
 				break;

 			default:

 				$content = "sucess";

		 		$result = $this->transmitText($object,$content); 

 				break;
 		
 		}
 		
   		return $result; 
 	}
 

 	/**
 	 * 生成xml格式数据echo给微信————文本
 	 * @param  [type] $object  [description]
 	 * @param  [type] $content [description]
 	 * @return [type]          [description]
 	 */
 	function transmitText($object,$content)
 	{ 	
   		$textTpl = "<xml> 
	       <ToUserName><![CDATA[%s]]></ToUserName> 
	       <FromUserName><![CDATA[%s]]></FromUserName> 
	       <CreateTime>%s</CreateTime> 
	       <MsgType><![CDATA[text]]></MsgType>
	       <Content><![CDATA[%s]]></Content> 
	       <FuncFlag>0</FuncFlag>
	       </xml>"; 
	    $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content); 
	    return $result; 
  	}

  	/**
  	 * [生成xml格式数据echo给微信————单图文]
  	 * @Author   zt
  	 * @DateTime 2018-01-12
  	 * @param    [type]     $object  [description]
  	 * @param    [type]     $title   [标题]
  	 * @param    [type]     $info    [说明]
  	 * @param    [type]     $img_url [图片地址]
  	 * @param    [type]     $url     [链接地址]
  	 * @return   [type]     $result  [xml字符串]
  	 */
	function transmitImg($object, $title, $info, $img_url, $url)
	{
		$imgTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[news]]></MsgType>
						<ArticleCount>1</ArticleCount>
						<Articles>
							<item>
								<Title><![CDATA[%s]]></Title>
								<Description><![CDATA[%s]]></Description>
								<PicUrl><![CDATA[%s]]></PicUrl>
								<Url><![CDATA[%s]]></Url>
							</item>
						</Articles>
					</xml>";
		$result = sprintf($imgTpl, $object->FromUserName, $object->ToUserName, time(), $title, $info, $img_url, $url);
		return $result;
	}
	
	/**
  	 * 回复统一消息
  	 * @param  [type] $object [description]
  	 * @return [type]         [description]
  	 */
  	function responseMsg($object)
  	{	
  		$content = "您的信息我们已经收到";
  		return $this->transmitText($object,$content);
  	}

  	/**
  	 * [关键字回复]
  	 * @Author   zt
  	 * @DateTime 2018-01-12
  	 * @param    [type]     $object [description]
  	 * @return   [type]             [description]
  	 */
  	function receiveText($object)
  	{
  		switch ($object->Content) {
  			case '抽奖':
  				$title = "年终抽奖活动";
  				$info = "这么好的奖品无论如何我都想送给您~";
  				$img_url = "http://xscall.oss-cn-hangzhou.aliyuncs.com/a75db0f83a034105ca76f1da5f1fde84.jpg";
  				$url = "https://w.url.cn/s/A1ln0Ff";
  				
  				break;
  			
  			case '#抽奖#':
  				$title = "年终抽奖活动";
  				$info = "这么好的奖品无论如何我都想送给您~";
  				$img_url = "http://xscall.oss-cn-hangzhou.aliyuncs.com/a75db0f83a034105ca76f1da5f1fde84.jpg";
  				$url = "https://w.url.cn/s/A1ln0Ff";
  				break;

  			default:
 				$content = "您的信息我们已经收到，24小时内会给您答复，请耐心等待";
  				break;
  		}

  		if (isset($content)) {
	 		$result = $this->transmitText($object,$content); 
  		} else {
  			$result = $this->transmitImg($object, $title, $info, $img_url, $url);
  		}
  		
 		return $result;
  	}
}